package com.financing.wap.web.controller.api;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.financing.wap.common.BizEnums.CommonEnums;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dto.FpShopUserRelProductDTO;
import com.financing.wap.dto.FpShopUserRelProductDetailDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IFpShopUserRelProductDetailService;
import com.financing.wap.service.IFpShopUserRelProductService;
import com.financing.wap.util.DTOdateSetUtil;
import com.financing.wap.util.StringUtil;
import com.financing.wap.vo.FpShopUserRelProductVO;
import com.financing.wap.web.controller.BaseController;

@Controller("fpShopUserRelProductController")
@RequestMapping("/api/fpShopUserRelProduct")
public class FpShopUserRelProductController extends BaseController  { 

	private Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private IFpShopUserRelProductService fpShopUserRelProductService;
	
	@Autowired
	private IFpShopUserRelProductDetailService fpShopUserRelProductDetailService;
	
	/***
	 * 用户新增产品
	 * @param request
	 * @param fpShopUserRelProduct
	 * @return
	 */
	@RequestMapping("/addFpShopUserRelProduct")
	@ResponseBody
	public ResultMap add(HttpServletRequest request, FpShopUserRelProductDTO fpShopUserRelProduct){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("add fpShopUserRelProduct  begin .......");
			
			UserDTO user = SessionUtil.getSession().getUser();
			fpShopUserRelProduct.setId(null);
			//参数校验
			initDto(fpShopUserRelProduct, result);
			if(!StringUtil.isNullOrEmptyStr(result.getStatusCode())){
				return result;
			}
			
			//新增  设置默认状态
			fpShopUserRelProduct.setRelUserId(user.getId());
			DTOdateSetUtil.setCreateInfo(fpShopUserRelProduct);
			DTOdateSetUtil.setUpdateInfo(fpShopUserRelProduct);
			fpShopUserRelProduct.setDeleteTag(CommonEnums.DELETE_FLAG_1);
			fpShopUserRelProduct.setPublicStatus("1");//默认发布
			
			int id = fpShopUserRelProductService.insert(fpShopUserRelProduct);
			result.setAttribute("id", id);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("add fpShopUserRelProduct list end .......");
		}catch(Exception e){
			log.error("add fpShopUserRelProduct error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	
	/***
	 * 处理数据
	 * @param fpShopUserRelProduct
	 * @param result
	 */
	private void initDto(FpShopUserRelProductDTO fpShopUserRelProduct,
			ResultMap result) {
		String productName = fpShopUserRelProduct.getProductName();
		String productType= fpShopUserRelProduct.getProductType();
		String saleStatus = fpShopUserRelProduct.getSaleStatus();
		String dueTime = fpShopUserRelProduct.getDueTime();
		String issuingScale = fpShopUserRelProduct.getIssuingScale();
		String revenue = fpShopUserRelProduct.getRevenue();
		//必填字段
		if(StringUtil.isNullOrEmptyNStr(productName,productType,saleStatus,dueTime,issuingScale,revenue)){
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
			result.setStatus(ResultMap.STATUS.FAILE);
			return ;
		}
		//获取起投金额
		Integer startAmount=null;
		String maxRevenue=null;
		
		//收益   处理空信息  排序
		JSONArray revenueJson=null;
		try {
			revenueJson=JSONArray.parseArray(revenue);
			
			//排序
			sortJsonArrayByDate(revenueJson, "minAmount", "int");
			
			for (int i = 0; i < revenueJson.size(); i++) {
				JSONObject revenueObject = revenueJson.getJSONObject(i);
				Integer minAmount = revenueObject.getInteger("minAmount");
				String revenueValue = revenueObject.getString("revenue");
				//初始化信息
				if(minAmount>0&&minAmount<10000&&!StringUtil.isNullOrEmptyNStr(revenueValue)){
					if(i==0 || startAmount== null){//首条取最小起够金额
						startAmount=minAmount;
					}
					if(i<revenueJson.size()-1){
						JSONObject revenueObjectbefore = revenueJson.getJSONObject(i+1);
						Integer max = revenueObjectbefore.getInteger("minAmount");
						revenueObject.put("maxAmount", max);
					}else{//结束取最大收益
						maxRevenue=revenueValue;
					}
				}
			}
		} catch (Exception e) {
			logger.error(" fpShopUserRelProduct  revenue error",e);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
			result.setStatus(ResultMap.STATUS.FAILE);
			return ;
		}
		//收益空间必须大于0
		if(revenueJson.size()==0){
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
			result.setStatus(ResultMap.STATUS.FAILE);
			return ;
		}
		//去除无效的收益信息  更新最大收益和起够金额
		fpShopUserRelProduct.setRevenue(revenueJson.toJSONString());
		fpShopUserRelProduct.setMinAmount(startAmount*10000);//前台单位为万
		fpShopUserRelProduct.setMaxRevenue(maxRevenue);
		//填写推荐理由
		String tuijianReson = fpShopUserRelProduct.getTuijianReson();
		if(StringUtil.isNullOrEmptyStr(tuijianReson)){
			fpShopUserRelProduct.setFlagTuijian("2");//未推荐
		}else{
			fpShopUserRelProduct.setFlagTuijian("1");//推荐
		}
	}

	/***
	 * 数组排序
	 * 
	 * @param array
	 * @param dateName
	 * @param type
	 */
	private void sortJsonArrayByDate(JSONArray array, final String dateName,
			final String type) {
		List<JSONObject> list = new ArrayList<JSONObject>();
		JSONObject jsonObj = null;
		for (int i = 0; i < array.size(); i++) {
			jsonObj = (JSONObject) array.get(i);
			if(jsonObj.get("minAmount")==null){
				continue;
			}
			list.add(jsonObj);
		}
		// 排序操作
		Collections.sort(list, new Comparator<JSONObject>() {
			@Override
			public int compare(JSONObject a, JSONObject b) {
				if ("int".equals(type.toLowerCase())) {
					try {
						Integer valA = a.getInteger(dateName);
						Integer valB = b.getInteger(dateName);
						return valA.compareTo(valB);
					} catch (JSONException e) {
						// do something
					}
				}
				String valA = new String();
				String valB = new String();
				try {
					valA = (String) a.get(dateName);
					valB = (String) b.get(dateName);
				} catch (JSONException e) {
					// do something
				}
				return valA.compareTo(valB);
			}
		});
		// 把数据放回去
		array.clear();
		for (int i = 0; i < list.size(); i++) {
			jsonObj = list.get(i);
			array.add(jsonObj);
		}
	}
	
	/***
	 * 用户关联产品详情
	 * @param request
	 * @param fpShopUserRelProduct
	 * @return
	 */
	@RequestMapping("/detailFpShopUserRelProduct")
	@ResponseBody
	public ResultMap detail(HttpServletRequest request, FpShopUserRelProductDTO fpShopUserRelProduct){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("query detail fpShopUserRelProduct  begin .......");
			
			Integer id = fpShopUserRelProduct.getId();
			
			if(id==null){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			
			FpShopUserRelProductDTO dto = fpShopUserRelProductService.loadById(id);
			
			//查询详情
			FpShopUserRelProductDetailDTO fpShopUserRelProductDetail=new FpShopUserRelProductDetailDTO();
			fpShopUserRelProductDetail.setDeleteTag(CommonEnums.DELETE_FLAG_1);
			fpShopUserRelProductDetail.setRelProductId(id);
			List<FpShopUserRelProductDetailDTO> q = fpShopUserRelProductDetailService.queryList(fpShopUserRelProductDetail);
			dto.setFpShopUserRelProductDetailList(q);
			
//			String publicStatus = dto.getPublicStatus();
//			if("1".equals(publicStatus)){
				result.setAttribute("dto",dto);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setStatus(ResultMap.STATUS.SUCCESS);
//			}else{
//				result.setStatusCode(ResultMap.PRODUCT_DOWN);
//				result.setStatus(ResultMap.STATUS.FAILE);
//			}
			
			//去除createdate、updatedate和delete_tag
			result.setAttribute("className", FpShopUserRelProductController.class.getName());
			result.setAttribute("methodName", "list");
			
			logger.info("query detail fpShopUserRelProduct  end .......");
		}catch(Exception e){
			log.error("query detail fpShopUserRelProduct error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	/** 放射 wap　过滤数据
	 * @param json
	 * @return
	 */
	public String waplist(String jsons){
		try {
			JSONObject json = JSON.parseObject(jsons);
			
			//获取  类名 方法名  进行放射
			JSONObject jo=json.getJSONObject("attributes");
			JSONObject dto = jo.getJSONObject("dto");
			//进行 多余字段过滤的数据
			dto.remove("createDate");
			dto.remove("createBy");
			dto.remove("updateDate");
			dto.remove("updateBy");
			dto.remove("deleteTag");
			JSONArray listArray = dto.getJSONArray("fpShopUserRelProductDetailList");
			for (int i = 0; i < listArray.size(); i++) {
				JSONObject jdto = (JSONObject) listArray.get(i);
				//进行 多余字段过滤的数据
				jdto.remove("createDate");
				jdto.remove("createBy");
				jdto.remove("updateDate");
				jdto.remove("updateBy");
			}
			return json.toJSONString();
		} catch (Exception e) {
			log.error("error  fundinfo WAPlist:",e);
			return jsons;
		}
	}
	/***
	 * 用户修改产品状态信息
	 * @param request
	 * @param fpShopUserRelProduct
	 * @return
	 */
	@RequestMapping("/updateFpShopUserRelProduct")
	@ResponseBody
	public ResultMap update(HttpServletRequest request, FpShopUserRelProductVO userRelProduct){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("update fpShopUserRelProduct  begin .......");
			
			String userId=SessionUtil.getSession().getUser().getId();
			
			Integer id = userRelProduct.getId();
			
			if(id==null){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			
			FpShopUserRelProductDTO relProduct = fpShopUserRelProductService.loadById(id);
			
			//校验产品是否为当前用户  不能修改
			if(relProduct.getRelUserId()==null||!userId.equals(relProduct.getRelUserId())){
				result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			FpShopUserRelProductDTO fpShopUserRelProduct=new FpShopUserRelProductDTO();
			//复制参数
			BeanUtils.copyProperties(userRelProduct, fpShopUserRelProduct);
			//参数校验
			initDto(fpShopUserRelProduct, result);
			if(!StringUtil.isNullOrEmptyStr(result.getStatusCode())){
				return result;
			}

			//不能修改的属性 默认属性
			fpShopUserRelProduct.setDeleteTag(relProduct.getDeleteTag());
			fpShopUserRelProduct.setPublicStatus(relProduct.getPublicStatus());
			DTOdateSetUtil.setUpdateInfo(fpShopUserRelProduct);
			
			fpShopUserRelProductService.update(fpShopUserRelProduct);
			
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("update fpShopUserRelProduct list end .......");
		}catch(Exception e){
			log.error("update fpShopUserRelProduct error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	
	/***
	 * 用户上下架产品
	 * @param request
	 * @param fpShopUserRelProduct
	 * @return
	 */
	@RequestMapping("/upFpShopUserRelProduct")
	@ResponseBody
	public ResultMap upFpShopUserRelProduct(HttpServletRequest request){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("upFpShopUserRelProduct  begin .......");
			
			String userId=SessionUtil.getSession().getUser().getId();
			
			String id = request.getParameter("id");
			String publicStatus=request.getParameter("publicStatus");
			
			if(StringUtil.isNullOrEmptyNStr(id,publicStatus)){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			
			FpShopUserRelProductDTO relProduct = fpShopUserRelProductService.loadById(Integer.parseInt(id));
			
			//校验产品是否为当前用户  不能修改
			if(relProduct.getRelUserId()==null||!userId.equals(relProduct.getRelUserId())){
				result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			
			FpShopUserRelProductDTO upPublicStatusDto=new FpShopUserRelProductDTO();
			if(!"1".equals(publicStatus)){
				publicStatus="2";
			}
			upPublicStatusDto.setPublicStatus(publicStatus);
			upPublicStatusDto.setId(Integer.parseInt(id));
			fpShopUserRelProductService.update(upPublicStatusDto);
			
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("upFpShopUserRelProduct end .......");
		}catch(Exception e){
			log.error("upFpShopUserRelProduct error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	
	/***
	 * 用户删除产品
	 * @param request
	 * @param fpShopUserRelProduct
	 * @return
	 */
	@RequestMapping("/deleteFpShopUserRelProduct")
	@ResponseBody
	public ResultMap delete(HttpServletRequest request){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("delete fpShopUserRelProduct  begin .......");
			
			UserDTO user = SessionUtil.getSession().getUser();
			
			String id = request.getParameter("id");
			
			if(StringUtil.isNullOrEmptyStr(id)||!id.matches("\\d+")){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			
			FpShopUserRelProductDTO fpShopUserRelProduct=new FpShopUserRelProductDTO();
			fpShopUserRelProduct.setId(Integer.parseInt(id));
			fpShopUserRelProduct.setDeleteTag(CommonEnums.DELETE_FLAG_2);
			fpShopUserRelProduct.setRelUserId(user.getId());
			
			fpShopUserRelProductService.update(fpShopUserRelProduct);
			
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("delete fpShopUserRelProduct end .......");
		}catch(Exception e){
			log.error("delete fpShopUserRelProduct error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
}
